package com.example.springboot.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.springboot.controller.VoteServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;


/**
 * @description: redis消息订阅-业务实现类
 * @author: Yuwl
 * @create: 2019-11-28 19:20
 **/
@Component
public class SubscribeMessage implements MessageListener {

	private static final Logger LOGGER = LoggerFactory.getLogger(SubscribeMessage.class);

	@Override
	public void onMessage(Message message, byte[] pattern) {
		String body = new String(message.getBody());
		String channel = new String(message.getChannel());
		String _pattern = new String(pattern);
		LOGGER.info("======================>>订阅到消息了：{}", body);
		JSONObject jsonObject = JSON.parseObject(body);
		JSONObject voteTopic = jsonObject.getJSONObject("data");
		try {
			VoteServerEndpoint.sendMessageAll(body, voteTopic.getInteger("id").toString());
		} catch (Exception e) {
			LOGGER.error("======================>>订阅到消息了：{}，通知websocket客户端报错了：{}", body, e);
		}
	}
}
